package com.hd.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.hd.dao.BaseDao;
import com.hd.domain.FieldVO;

public class BaseDaoImpl extends HibernateDaoSupport implements BaseDao{

	public boolean save() {
		return false;
	}
	public Map<String,Object> getData(String sql) throws Exception{
		Map<String,Object> resultMap = null;
		Connection con = null;;
		PreparedStatement psmt = null;
		ResultSet rs = null;
		try{
			Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
			con = session.connection();
			psmt = con.prepareStatement(sql);
			rs = psmt.executeQuery();
			ResultSetMetaData rsmd = psmt.getMetaData();
			int columnCount = rsmd.getColumnCount();
			List<FieldVO> fields = new ArrayList<FieldVO>(columnCount);
			FieldVO field = null;
			for(int i=1;i<=columnCount;i++){
				field = new FieldVO();
				field.setName(rsmd.getColumnLabel(i));
				field.setInt(rsmd.getColumnTypeName(i).contains("INT"));
				fields.add(field);
			}
			resultMap = new HashMap<String,Object>(columnCount);
			if(rs.next()){
				for(FieldVO f:fields){
					if(f.isInt()){
						resultMap.put(f.getName(), rs.getInt(f.getName()));
					}else{
						resultMap.put(f.getName(), rs.getString(f.getName()));
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(rs!=null){
				rs.close();
			}
			if(psmt!=null){
				psmt.close();
			}
			if(con!=null){
				con.close();
			}
		}
		return resultMap;
	}
}
